<?php
/**
 * User: aka
 * Time: 16:42
 */

namespace app\plug\controller;

use app\validator\plug\SendEmailCode;
use think\facade\Session;
use think\Request;

class Mail
{
    public $emailPlug;
    private $emailCode;
    private $receiveAddress;

    public function __construct()
    {
        $this->emailPlug = new \app\common\plug\Mail();
        $this->emailCode = get_six_code();
        $this->receiveAddress = null;
    }

    public function __destruct()
    {
        unset(
            $this->emailPlug,
            $this->emailCode,
            $this->receiveAddress
        );
    }

    public function sendEmailCode(Request $request)
    {
        $validate = new SendEmailCode();
        if (!$validate->check($request->param())) {
            return json($validate->getError());
        }else {
            $this->emailPlug->setSendName(config('site_des.site_boss_name'));
            $this->emailPlug->setEmailTitle(config('app.app_name') . ' - ' . config('site_des.site_email_code_title'));
            $this->emailPlug->setEmailContent($this->emailCode);
            $this->receiveAddress = $request->param('email_address');
            $this->emailPlug->setReceiveAddress($this->receiveAddress);
            $this->saveEmailSession();
            return $this->emailPlug->send();
        }
    }

    private function saveEmailSession()
    {
        Session::set('email_code', $this->emailCode);
    }
}